package com.tree.commonutil.csv;

import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.tree.commonutil.TbCar;
import org.apache.tomcat.util.buf.CharsetUtil;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.IOUtils;

import java.io.*;
import java.util.List;

/**
 * @ClassName CsvDemo2
 * @Description: 注解映射
 * @Author: myl
 * @Create_time:2021/5/7 14:29
 */
public class CsvDemo2 {
    public static void main(String[] args) throws IOException {

        File file = new File("D:\\document\\download-context\\bop.csv");
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", input);

        InputStreamReader inputStream = new InputStreamReader(multipartFile.getInputStream(), "GBK");
        // 设置解析策略，csv的头和POJO属性的名称对应，也可以使用@CsvBindByName注解来指定名称
        HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy();
        strategy.setType(TbCar.class);

        CsvToBean csvToBean = new CsvToBeanBuilder(inputStream)
                .withMappingStrategy(strategy)
                .build();
        List carCsvDTOList = csvToBean.parse();
        carCsvDTOList.forEach(item -> System.out.println(item.toString()));
    }
}
